package com.SoftwareManage.controller;

import com.SoftwareManage.entity.Cae;
import com.SoftwareManage.service.CaeService;
import com.SoftwareManage.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@Controller
@RequestMapping("/cae")
public class CaeController {
    @Autowired
    private CaeService caeService;

    private final static Logger logger = LoggerFactory.getLogger(CaeController.class);

    //跳转到cae页面
    @RequestMapping("/cae")
    public String toCae(Model model,HttpServletRequest request){
        String ip= IpUtil.getIpAddr(request);
        logger.info(ip+"------跳转到cae信息页面------");
        List<Cae> softwares=caeService.selectAll();
        model.addAttribute("number",softwares.size());
        return "cae";
    }

    //cae页面list回调函数请求所有数据
    @RequestMapping(value = "/lists")
    @ResponseBody
    public Map<String, Object> showEntity(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit) throws IOException {
        List<Cae> entities = caeService.selectAll();
        int pageNum = (page - 1) * limit;
        List<Cae> entity = caeService.selectAlls(pageNum, limit);

        Map<String, Object> tableData = new HashMap<String, Object>();
        //这是layui要求返回的json数据格式
        tableData.put("code", 0);
        tableData.put("msg", "");
        //将全部数据的条数作为count传给前台（一共多少条）
        tableData.put("count", entities.size());
        //将分页后的数据返回（每页要显示的数据）
        tableData.put("data", entity);
        //返回给前端
        return tableData;
    }

    //查询信息
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> search(
            @RequestParam(required = false) String software,
            @RequestParam(required = false) String person,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit
    ) {
        Map<String, Object> tableData = new HashMap<String, Object>();
        List<Cae> entities=caeService.search(software,person);
        int pageNum = (page - 1) * limit;
        List<Cae> entity = caeService.searchs(software,person,pageNum, limit);
        tableData.put("code", 0);
        tableData.put("msg", "");
        //将全部数据的条数作为count传给前台（一共多少条）
        tableData.put("count", entities.size());
        //将分页后的数据返回（每页要显示的数据）
        tableData.put("data", entity);
        //返回给前端
        return tableData;
    }

    //	修改信息
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> editEntity(
            @RequestParam("id") int id,
            @RequestParam("software") String software,
            @RequestParam("person") String person,
            @RequestParam("ip") String ip,
            @RequestParam("server") String server,
            @RequestParam("address") String address,
            @RequestParam("port") String port,
            @RequestParam("datedue") Date datedue,
            @RequestParam("license") String o_license,
            @RequestParam("n_license") MultipartFile file,
            @RequestParam("remark") String remark,
            HttpServletRequest request) throws UnsupportedEncodingException {
        String ipAddr= IpUtil.getIpAddr(request);
        Map<String, Object> tableData = new HashMap<String, Object>();
        String license = file.getOriginalFilename();// 获取文件名
        if (license.isEmpty()) {
            license = o_license;
        }
        String filePath = "D:/SoftwareData/license/";
        File dest = new File(filePath + license);
        // 判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
        }
        caeService.update(id, software, person, ip, server, address,port,datedue,license,remark);
        tableData.put("code", 100);
        tableData.put("msg", "");
        //将全部数据的条数作为count传给前台（一共多少条）
        tableData.put("count", 0);
        //将分页后的数据返回（每页要显示的数据）
        tableData.put("data", "");
        logger.info(ipAddr+"------[cae]修改成功------");
        //返回给前端
        return tableData;
    }

    //	添加信息
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addEntity(
            @RequestParam("a_software") String software,
            @RequestParam("a_person") String person,
            @RequestParam("a_ip") String ip,
            @RequestParam("a_server") String server,
            @RequestParam("a_address") String address,
            @RequestParam("a_port") String port,
            @RequestParam("a_datedue") Date datedue,
            @RequestParam("a_license") MultipartFile file,
            @RequestParam("a_remark") String remark,
            HttpServletRequest request) throws UnsupportedEncodingException {
        String ipAddr= IpUtil.getIpAddr(request);
        Map<String, Object> tableData = new HashMap<String, Object>();
        List<String> softwares=caeService.selectAllSoftwares();
        if (softwares.contains(software)){
            tableData.put("code", 300);
            tableData.put("msg", "软件名已存在！");
            //将全部数据的条数作为count传给前台（一共多少条）
            tableData.put("count", 0);
            //将分页后的数据返回（每页要显示的数据）
            tableData.put("data", "");
            logger.info("------[cae]添加失败------");
            //返回给前端
            return tableData;
        }
        String license = file.getOriginalFilename();// 获取文件名
        String filePath = "D:/SoftwareData/license/";
        File dest = new File(filePath + license);
        // 判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
        }
        caeService.add(software,person,ip,server,address,port,datedue,license,remark);
        tableData.put("code", 200);
        tableData.put("msg", "添加成功！");
        //将全部数据的条数作为count传给前台（一共多少条）
        tableData.put("count", 0);
        //将分页后的数据返回（每页要显示的数据）
        tableData.put("data", "");
        logger.info(ipAddr+"------[cae]添加成功------");
        //返回给前端
        return tableData;
    }

    //删除信息
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> removeEntity(@RequestBody int[] ids,
                                            HttpServletRequest request) {
        String ipAddr= IpUtil.getIpAddr(request);
        Map<String, Object> tableData = new HashMap<String, Object>();
        for (int id : ids) {
            caeService.delete(id);
        }
        tableData.put("code", 300);
        tableData.put("msg", "");
        //将全部数据的条数作为count传给前台（一共多少条）
        tableData.put("count", 0);
        //将分页后的数据返回（每页要显示的数据）
        tableData.put("data", "");
        logger.info(ipAddr+"------[cae]删除成功------");
        //返回给前端
        return tableData;
    }

    // 下载许可文件
    @GetMapping(value = "/download")
    public String download(HttpServletResponse res,
                           Model model,
                           @RequestParam("id") int id,
                           HttpServletRequest request) throws IOException {
        String ipAddr= IpUtil.getIpAddr(request);
        Cae entity=caeService.findById(id);
        String fileName = entity.getLicense();
        if (fileName==null){
            model.addAttribute("msg","许可文件不存在！");
            return "message";
        }
        res.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        res.setContentType("content-type:octet-stream");
        BufferedInputStream inputStream= new BufferedInputStream(new FileInputStream(new File("D:/SoftwareData/license/" + fileName)));
        OutputStream outputStream = res.getOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0 ;
        while ((len = inputStream.read(buffer)) != -1){
            outputStream.write(buffer ,0 , len);
    }
        inputStream.close();
        outputStream.close();
        logger.info(ipAddr+"------[cae]下载成功------");
        return null;
    }

}
